import path from 'path';
import log4js from 'log4js';
import store from '../store';
import osUtils from '../../../common/help/os';

// 注意：不要引入 util.js 文件，有依赖问题

const pattern = '[%d{yyyy-MM-dd hh:mm:ss}]%n%n%m%n%n%n';

function getLogFileName() {
    const d = new Date();
    const year = d.getFullYear();
    let month = '' + (d.getMonth() + 1);
    let date = '' + d.getDate();

    if (+month < 10) {
        month = '0' + month;
    }
    if (+date < 10) {
        date = '0' + date;
    }
    return `${year}${month}${date}`;
}

function dirname(dir: string) {
    return path.resolve(store.state.isDev ? path.join(__dirname, '..', '..') : osUtils.getAppDataPath(), 'logFile', dir);
}

function filename(dir: string) {
    return path.join(dirname(dir), getLogFileName() + '.log');
}

log4js.configure({
    appenders: {
        log: { type: 'file', filename: filename('service-log'), layout: { type: 'pattern', pattern } },
        req: { type: 'file', filename: filename('service-request'), layout: { type: 'pattern', pattern } },
        res: { type: 'file', filename: filename('service-response'), layout: { type: 'pattern', pattern } },
        error: { type: 'file', filename: filename('service-error'), layout: { type: 'pattern', pattern } },
        fetchError: { type: 'file', filename: filename('service-fetch-error'), layout: { type: 'pattern', pattern } },
    },

    categories: {
        default: { appenders: ['log'], level: 'all' },
        req: { appenders: ['req'], level: 'all' },
        res: { appenders: ['res'], level: 'all' },
        error: { appenders: ['error'], level: 'error' },
        fetchError: { appenders: ['fetchError'], level: 'error' },
    },
});

export function log(message: unknown): void {
    log4js.getLogger().info(message);
}

export function reqLog(message: unknown): void {
    log4js.getLogger('req').info(message);
}

export function resLog(message: unknown): void {
    log4js.getLogger('res').info(message);
}

export function errLog(error: unknown): void {
    log4js.getLogger('error').error(error);
}

export function fetchErrLog(message: unknown): void {
    log4js.getLogger('fetchError').error(message);
}
